import axios from 'axios';
import { getApiConfig } from '../config/api.js';

// 创建 API 请求实例工厂函数
const createApiInstance = (system, headerOptions) => {
  const config = getApiConfig(system);
  
  const instance = axios.create({
    baseURL: config.baseURL,
    timeout: config.timeout,
    headers: {
      'Accept': 'application/json'
    }
  });

  // 请求拦截器
  instance.interceptors.request.use(
    config => {
      if (headerOptions) {
        config.headers = {
          ...config.headers,
          ...headerOptions(config.headers)
        }
      }

      // if (!config.headers.token && !config.headers.Authorization) {
      //   return Promise.reject({
      //     message: 'token已过期，请重新打开',
      //     code: 401
      //   });
      // }

      // 检查是否是 URLSearchParams 数据
      if (config.data instanceof URLSearchParams) {
        config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
      }

      return config;
    },
    error => {
      return Promise.reject(error);
    }
  );

  // 响应拦截器
  instance.interceptors.response.use(
    response => {
      return response;
    },
    error => {
      // console.error('6666:', error);
      return Promise.reject(error);
    }
  );

  return instance;
};

// 导出不同系统的 API 实例
export const waterApi = createApiInstance('waterSystem', config => ({ 
  'Authorization': `Bearer ${config.token}`
}));
export const shjApi = createApiInstance('shjSystem', config => ({ 
  'token': config.token
}));
export const shjTestApi = createApiInstance('shjTestSystem', config => ({ 
  'token': config.token
}));
export const psApi = createApiInstance('psSystem', config => ({ 
  'Authorization': `Bearer ${config.token}`
}));
export const selfApi = createApiInstance('selfSystem');

// 默认导出水利系统的 API 实例
export default waterApi; 